package com.zxcl.listener;

import com.alibaba.fastjson.JSON;
import com.aliyun.dysmsapi20170525.Client;
import com.aliyun.dysmsapi20170525.models.SendSmsRequest;
import com.aliyun.dysmsapi20170525.models.SendSmsResponse;
import com.zxcl.constant.MqConstant;
import com.zxcl.domain.SmsLog;
import com.zxcl.model.AliSmsModel;
import com.zxcl.service.SmsLogService;
import org.apache.rocketmq.common.message.MessageExt;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * 描述: [短信监听类]
监听mq中的消息
 * 作者: zxcl
 */
@Component
@RocketMQMessageListener(topic = MqConstant.ALI_SMS_TOPIC, consumerGroup = MqConstant.ALI_SMS_CONSUMER_GROUP, namespace = MqConstant.MQ_NAME_SPACE)
public class AliSmsListener implements RocketMQListener<MessageExt> {

    @Autowired
    private Client client;

    @Autowired
    private SmsLogService smsLogService;

    /**
     * 生产者传递的是实参 {手机号码，签名，模板 变量}
     * mq的消费者 接收到的消息 形参
     *
     * @param message
     */
    @Override
    public void onMessage(MessageExt message) {
        AliSmsModel aliSmsModel = JSON.parseObject(new String(message.getBody()), AliSmsModel.class);

        SendSmsRequest smsRequest = new SendSmsRequest();
        smsRequest.setPhoneNumbers(aliSmsModel.getPhoneNumber());
        smsRequest.setSignName(aliSmsModel.getSignName());
        smsRequest.setTemplateCode(aliSmsModel.getTemplateCode());
        smsRequest.setTemplateParam(aliSmsModel.getTemplateParam());

        SendSmsResponse sendSmsResponse = null;
        SmsLog sms=new SmsLog();

        try {
            sendSmsResponse = client.sendSms(smsRequest);
        } catch (Exception e) {
            e.printStackTrace();
            sms.setStatus(1);
        }
        // todo 保存到数据库
        System.out.println(sendSmsResponse.getBody());
        sms.setCreateTime(new Date());
        sms.setMobileCode(sendSmsResponse.getBody().getCode());
        sms.setTemplateId(aliSmsModel.getTemplateCode());
        sms.setUserPhone(smsRequest.getPhoneNumbers());
        sms.setOpenId(aliSmsModel.getOpenId());
        sms.setResponseCode(sendSmsResponse.getBody().getCode());
        smsLogService.save(sms);
    }
}
